package app.itgungnir.compose.wan.business.main.mine

import androidx.lifecycle.ViewModel
import app.itgungnir.compose.wan.CoinInfo
import app.itgungnir.compose.wan.WanApp
import app.itgungnir.compose.wan.utils.*
import com.google.gson.JsonObject
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.map

class MineViewModel : ViewModel() {

    val loadingState = MutableStateFlow(false)
    val errorState = MutableSharedFlow<Throwable?>()
    val dialogErrorState = MutableSharedFlow<Throwable?>()
    val dismissDialogState = MutableStateFlow(false)
    var loadingJob: Job? = null

    val hasLoginFlow = WanApp.instance.dataStore.data.map { it.hasLogin }
    val userInfoFlow = WanApp.instance.dataStore.data.map { it.userInfo }
    val coinInfoFlow = WanApp.instance.dataStore.data.map { it.coinInfo }

    init {
        getUserInfo()
    }

    fun getUserInfo() = launch {
        if (!LocalDataStore.localData.hasLogin) {
            return@launch
        }
        val response: UserCoinInfo? = try {
            wanAndroidService.getUserCoinInfo().wanResponse<UserCoinInfo>()
        } catch (e: Exception) {
            e.printStackTrace()
            errorState.emit(e)
            null
        }
        response?.let {
            LocalDataStore.updateLocalData {
                it.coinInfo = CoinInfo.newBuilder().apply {
                    this.coins = response.coinCount
                    this.level = response.level
                    this.rank = response.rank
                }.build()
            }
        }
    }

    fun logout() = launch(loadingState = loadingState, errorState = dialogErrorState) {
        dismissDialogState.value = false
        wanAndroidService.logout().wanResponse<JsonObject>()
        WanDatabase.instance.onUserLogout()
        dismissDialogState.value = true
    }.also { loadingJob = it }
}
